<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>SimplerWorker聊天室</title>
    <link href="__STATIC__/chat/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="__STATIC__/chat/js/jquery.min.js"></script>
    <script type="text/javascript">

        var ws,client_id;
        function connect() {
            // 1. 与gateway建立webSocket连接
            ws = new WebSocket("ws://" + document.domain + ":8082");
            ws.onmessage = onmessage;
            ws.onclose = function () {
                console.log("连接关闭，定时重连");
                connect();
            };
            ws.onerror = function () {
                console.log("出现错误");
            };
        }

        function onmessage(e) {
            // json数据转换成js对象
            var data = eval("("+e.data+")");
            var type = data.type || '';
            switch(type){
                    // 2. businessworker的Events.php中返回{"type":"init","client_id":"7f00000108fc00000001"}给客户端
                case 'init':
                    client_id = data.client_id;
                    // 3. 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
                    $.post('./initUser', {'client_id': client_id,'uid':1}, function(data){}, 'json');
                    break;
                    // 4. thinkPHP框架调用GatewayClient发来的消息，根据文档进行具体操作
                default :
                    console.dir(e.data);
            }
        }

        function onSubmit() {
            $.post('./doSomeThing', {'client_id': client_id,'uid':1}, function(data){}, 'json');
        }

        connect();

    </script>
</head>

<form onsubmit="onSubmit(); return false;">
    <div class="say-btn">
        <input type="submit" class="btn btn-success"  value="发送"/>
    </div>
</form>

</body>
</html>
